<template>
  <div class="order-detail-container">
    <div class="page-header">
      <div class="header-title">
        <h2>订单详情</h2>
        <el-button icon="el-icon-back" @click="goBack">返回列表</el-button>
      </div>
    </div>

    <div v-loading="loading">
      <!-- 订单基本信息卡片 -->
      <el-card class="detail-card">
        <div slot="header" class="card-header">
          <span class="card-title">基本信息</span>
          <el-tag :type="getStatusType(orderDetail.status)">{{ getStatusText(orderDetail.status) }}</el-tag>
        </div>
        
        <el-row :gutter="20" class="info-row">
          <el-col :span="8">
            <div class="info-item">
              <span class="label">订单编号：</span>
              <span class="value">{{ orderDetail.orderNo || '—' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">下单时间：</span>
              <span class="value">{{ formatDateTime(orderDetail.createdTime) }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">支付时间：</span>
              <span class="value">{{ orderDetail.payTime ? formatDateTime(orderDetail.payTime) : '未支付' }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20" class="info-row">
          <el-col :span="8">
            <div class="info-item">
              <span class="label">订单金额：</span>
              <span class="value price">¥{{ formatPrice(orderDetail.totalAmount) }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">支付金额：</span>
              <span class="value price">¥{{ formatPrice(orderDetail.payAmount) }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">支付方式：</span>
              <span class="value">{{ getPaymentMethod(orderDetail.payMethod) }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 用户信息卡片 -->
      <el-card class="detail-card">
        <div slot="header" class="card-header">
          <span class="card-title">用户信息</span>
        </div>
        
        <el-row :gutter="20" class="info-row">
          <el-col :span="8">
            <div class="info-item">
              <span class="label">用户ID：</span>
              <span class="value">{{ orderDetail.userId || '—' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">用户名：</span>
              <span class="value">{{ orderDetail.username || '—' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">联系方式：</span>
              <span class="value">{{ orderDetail.userPhone || '—' }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 收货信息卡片 -->
      <el-card class="detail-card">
        <div slot="header" class="card-header">
          <span class="card-title">收货信息</span>
        </div>
        
        <el-row :gutter="20" class="info-row">
          <el-col :span="8">
            <div class="info-item">
              <span class="label">收货人：</span>
              <span class="value">{{ orderDetail.receiverName || '—' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">联系电话：</span>
              <span class="value">{{ orderDetail.receiverPhone || '—' }}</span>
            </div>
          </el-col>
          <el-col :span="24">
            <div class="info-item">
              <span class="label">收货地址：</span>
              <span class="value">{{ orderDetail.receiverAddress || '—' }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 订单商品信息 -->
      <el-card class="detail-card">
        <div slot="header" class="card-header">
          <span class="card-title">商品信息</span>
        </div>
        
        <el-table :data="orderDetail.orderItems || []" border style="width: 100%">
          <el-table-column type="index" label="#" width="60" align="center"></el-table-column>
          <el-table-column label="商品图片" width="100" align="center">
            <template slot-scope="scope">
              <el-image 
                style="width: 60px; height: 60px" 
                :src="scope.row.imageUrl || 'https://via.placeholder.com/60'" 
                fit="cover"
                :preview-src-list="[scope.row.imageUrl || 'https://via.placeholder.com/60']">
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="flowerId" label="商品ID" width="80" align="center"></el-table-column>
          <el-table-column prop="flowerName" label="商品名称" min-width="200"></el-table-column>
          <el-table-column prop="price" label="单价" width="100" align="right">
            <template slot-scope="scope">
              ¥{{ formatPrice(scope.row.price) }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="80" align="center"></el-table-column>
          <el-table-column label="小计" width="120" align="right">
            <template slot-scope="scope">
              ¥{{ formatPrice(scope.row.price * scope.row.quantity) }}
            </template>
          </el-table-column>
        </el-table>
        
        <div class="order-summary">
          <div class="summary-item">
            <span class="label">商品总价：</span>
            <span class="value">¥{{ formatPrice(calculateSubtotal()) }}</span>
          </div>
          <div class="summary-item">
            <span class="label">运费：</span>
            <span class="value">¥{{ formatPrice(orderDetail.freightAmount || 0) }}</span>
          </div>
          <div class="summary-item">
            <span class="label">优惠金额：</span>
            <span class="value">-¥{{ formatPrice(orderDetail.discountAmount || 0) }}</span>
          </div>
          <div class="summary-item total">
            <span class="label">实付金额：</span>
            <span class="value price">¥{{ formatPrice(orderDetail.payAmount || 0) }}</span>
          </div>
        </div>
      </el-card>

      <!-- 订单日志 -->
      <el-card class="detail-card">
        <div slot="header" class="card-header">
          <span class="card-title">订单日志</span>
        </div>
        
        <el-timeline>
          <el-timeline-item
            v-for="(activity, index) in orderDetail.orderLogs || []"
            :key="index"
            :timestamp="formatDateTime(activity.createTime)"
            :color="getLogColor(activity.operateType)">
            {{ activity.logContent }}
          </el-timeline-item>
          <el-timeline-item 
            v-if="!orderDetail.orderLogs || orderDetail.orderLogs.length === 0"
            timestamp="暂无日志" 
            :color="'gray'">
            无订单操作记录
          </el-timeline-item>
        </el-timeline>
      </el-card>

      <!-- 操作按钮区域 -->
      <div class="action-container">
        <el-button @click="goBack">返回</el-button>
        <el-button type="primary" @click="handlePrint">打印订单</el-button>
        <el-button type="warning" @click="updateOrderStatus" :disabled="orderDetail.status === 4">修改状态</el-button>
        <el-button type="danger" @click="confirmDelete">删除订单</el-button>
      </div>
    </div>

    <!-- 修改订单状态对话框 -->
    <el-dialog title="修改订单状态" :visible.sync="statusDialogVisible" width="30%">
      <el-form :model="statusForm" label-width="100px">
        <el-form-item label="当前状态">
          <el-tag :type="getStatusType(orderDetail.status)">
            {{ getStatusText(orderDetail.status) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="新状态">
          <el-select v-model="statusForm.newStatus" placeholder="请选择新状态">
            <el-option label="待支付" :value="0" :disabled="orderDetail.status === 0"></el-option>
            <el-option label="待发货" :value="1" :disabled="orderDetail.status === 1"></el-option>
            <el-option label="待收货" :value="2" :disabled="orderDetail.status === 2"></el-option>
            <el-option label="已完成" :value="3" :disabled="orderDetail.status === 3"></el-option>
            <el-option label="已取消" :value="4" :disabled="orderDetail.status === 4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="statusForm.remark" rows="3"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="statusDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmUpdateStatus">确定</el-button>
      </span>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      title="确认删除"
      :visible.sync="deleteDialogVisible"
      width="30%">
      <span>确定要删除该订单吗？此操作不可恢复！</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDeleteOrder">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'AdminOrderDetail',
  props: {
    id: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      loading: false,
      orderDetail: {},
      statusDialogVisible: false,
      deleteDialogVisible: false,
      statusForm: {
        newStatus: '',
        remark: ''
      }
    };
  },
  created() {
    this.fetchOrderDetail();
  },
  methods: {
    fetchOrderDetail() {
      this.loading = true;
      this.request.get(`/orders/admin/detail/${this.id}`)
        .then(res => {
          if (res.code === 1) {
            this.orderDetail = res.data || {};
          } else {
            this.$message.error(res.msg || '获取订单详情失败');
          }
        })
        .catch(err => {
          console.error('Failed to fetch order detail:', err);
          this.$message.error('获取订单详情失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    goBack() {
      this.$router.go(-1);
    },
    formatDateTime(dateTime) {
      if (!dateTime) return '—';
      const date = new Date(dateTime);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
    },
    formatPrice(price) {
      return parseFloat(price || 0).toFixed(2);
    },
    getStatusType(status) {
      const typeMap = {
        0: 'warning',  // 待支付
        1: 'primary',  // 待发货
        2: 'success',  // 待收货
        3: 'info',     // 已完成
        4: 'danger'    // 已取消
      };
      return typeMap[status] || '';
    },
    getStatusText(status) {
      const statusMap = {
        0: '待支付',
        1: '待发货',
        2: '待收货',
        3: '已完成',
        4: '已取消'
      };
      return statusMap[status] || '未知状态';
    },
    getPaymentMethod(method) {
      const methodMap = {
        1: '支付宝',
        2: '微信支付',
        3: '银行卡',
        4: '货到付款'
      };
      return methodMap[method] || '未支付';
    },
    getLogColor(type) {
      const colorMap = {
        'create': '#409EFF',
        'pay': '#67C23A',
        'ship': '#E6A23C',
        'receive': '#409EFF',
        'finish': '#67C23A',
        'cancel': '#F56C6C'
      };
      return colorMap[type] || '#909399';
    },
    calculateSubtotal() {
      if (!this.orderDetail.orderItems || this.orderDetail.orderItems.length === 0) {
        return 0;
      }
      return this.orderDetail.orderItems.reduce((total, item) => {
        return total + (item.price * item.quantity);
      }, 0);
    },
    handlePrint() {
      window.print();
    },
    updateOrderStatus() {
      this.statusForm.newStatus = '';
      this.statusForm.remark = '';
      this.statusDialogVisible = true;
    },
    confirmUpdateStatus() {
      if (!this.statusForm.newStatus) {
        this.$message.warning('请选择新状态');
        return;
      }

      const params = {
        orderId: this.id,
        status: this.statusForm.newStatus,
        remark: this.statusForm.remark
      };

      this.request.put('/orders/admin/updateStatus', params)
        .then(res => {
          if (res.code === 1) {
            this.$message.success('订单状态更新成功');
            this.statusDialogVisible = false;
            this.fetchOrderDetail(); // 重新获取订单详情
          } else {
            this.$message.error(res.msg || '订单状态更新失败');
          }
        })
        .catch(err => {
          console.error('Failed to update order status:', err);
          this.$message.error('订单状态更新失败');
        });
    },
    confirmDelete() {
      this.deleteDialogVisible = true;
    },
    confirmDeleteOrder() {
      this.request.delete(`/orders/admin/delete/${this.id}`)
        .then(res => {
          if (res.code === 1) {
            this.$message.success('订单删除成功');
            this.deleteDialogVisible = false;
            this.$router.push('/adminhome'); // 删除后返回首页
          } else {
            this.$message.error(res.msg || '订单删除失败');
          }
        })
        .catch(err => {
          console.error('Failed to delete order:', err);
          this.$message.error('订单删除失败');
        });
    }
  }
};
</script>

<style scoped>
.order-detail-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  align-items: center;
}

.header-title h2 {
  margin: 0 20px 0 0;
  font-size: 22px;
  color: #303133;
}

.detail-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.info-row {
  margin-bottom: 15px;
}

.info-item {
  margin-bottom: 10px;
}

.info-item .label {
  color: #909399;
  margin-right: 8px;
}

.info-item .value {
  color: #303133;
  font-weight: 500;
}

.info-item .value.price {
  color: #F56C6C;
}

.order-summary {
  margin-top: 20px;
  border-top: 1px dashed #EBEEF5;
  padding-top: 20px;
  text-align: right;
}

.summary-item {
  margin-bottom: 10px;
}

.summary-item .label {
  color: #909399;
  margin-right: 8px;
}

.summary-item .value {
  color: #303133;
  font-weight: 500;
}

.summary-item.total {
  font-size: 16px;
  margin-top: 15px;
  border-top: 1px solid #EBEEF5;
  padding-top: 15px;
}

.summary-item.total .value {
  color: #F56C6C;
  font-weight: bold;
}

.action-container {
  margin-top: 30px;
  text-align: center;
}

/* 打印样式 */
@media print {
  .page-header, .action-container, .el-dialog__wrapper {
    display: none !important;
  }
  
  .order-detail-container, .detail-card {
    background-color: white !important;
    padding: 0 !important;
    box-shadow: none !important;
  }
}
</style> 